package com.lfy.yunpicture.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.lfy.yunpicture.annotation.AuthCheck;
import com.lfy.yunpicture.api.aliyun.model.CreateOutPaintingTaskResponse;
import com.lfy.yunpicture.api.aliyun.model.GetOutPaintingTaskResponse;
import com.lfy.yunpicture.common.*;
import com.lfy.yunpicture.constant.UserConstant;
import com.lfy.yunpicture.exception.BusinessException;
import com.lfy.yunpicture.exception.ThrowUtils;
import com.lfy.yunpicture.manager.auth.StpKit;
import com.lfy.yunpicture.manager.auth.annotate.SaSpaceCheckPermission;
import com.lfy.yunpicture.manager.auth.model.SpaceUserPermissionConstant;
import com.lfy.yunpicture.mapper.CategoryMapper;
import com.lfy.yunpicture.mapper.FormatsMapper;
import com.lfy.yunpicture.mapper.TagsMapper;
import com.lfy.yunpicture.model.dto.ai.PictureAiRequest;
import com.lfy.yunpicture.model.dto.file.*;
import com.lfy.yunpicture.model.entity.*;
import com.lfy.yunpicture.model.enums.ReviewStatusEnum;
import com.lfy.yunpicture.model.vo.CateGoryAndTagVO;
import com.lfy.yunpicture.model.vo.PictureVO;
import com.lfy.yunpicture.service.PictureService;
import com.lfy.yunpicture.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 文件接口
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;
    @Resource
    private PictureService pictureService;
    @Resource
    private TagsMapper tagsMapper;
    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private FormatsMapper formatsMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    // redis key
    private static final String REDIS_KEY_PREFIX = "picture:list:";

    /**
     * 文件上传
     *
     * @param multipartFile
     * @param uploadPictureRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<PictureVO> uploadFile(@RequestPart("file") MultipartFile multipartFile,
                                              UploadPictureRequest uploadPictureRequest, HttpServletRequest request) {
        // 参数检验
        ThrowUtils.throwIf(multipartFile == null, new BusinessException(ErrorCode.PARAMS_ERROR));
        // 上传图片，返回图片基本信息
        PictureVO pictureVO = pictureService.uploadFile(multipartFile, uploadPictureRequest, request);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 根据Url上传
     *
     * @param uploadPictureRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/url")
    public BaseResponse<PictureVO> uploadFileUrl(UploadPictureRequest uploadPictureRequest, HttpServletRequest request) {
        // 参数检验
        ThrowUtils.throwIf(uploadPictureRequest == null, new BusinessException(ErrorCode.PARAMS_ERROR));
        // 上传图片，返回图片基本信息
        PictureVO pictureVO = pictureService.uploadFileUrl(uploadPictureRequest, request);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 批量上传
     *
     * @param pictureBatchUploadRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadBatchFile(PictureBatchUploadRequest pictureBatchUploadRequest, HttpServletRequest request) {
        // 参数检验
        ThrowUtils.throwIf(pictureBatchUploadRequest == null, new BusinessException(ErrorCode.PARAMS_ERROR));
        // 上传图片，返回图片基本信息
        Integer count = pictureService.pictureBatchUpload(pictureBatchUploadRequest, request);
        return ResultUtils.success(count);
    }
    // region 增删改查

    /**
     * 创建图片
     *
     * @param pictureAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addPicture(@RequestBody PictureAddRequest pictureAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureAddRequest == null, ErrorCode.PARAMS_ERROR);
        long newPictureId = pictureService.addPicture(pictureAddRequest, request);
        return ResultUtils.success(newPictureId);
    }

    /**
     * 删除图片
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        pictureService.deletePicture(deleteRequest.getId(), request);
        return ResultUtils.success(true);
    }

    /**
     * 批量删除图片
     * @param deleteBatchRequest
     * @return
     */
     @PostMapping("/delete/batch")
     @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
     public BaseResponse<Boolean> deleteBatchPicture(@RequestBody DeleteBatchRequest deleteBatchRequest) {
         ThrowUtils.throwIf(deleteBatchRequest == null, ErrorCode.PARAMS_ERROR);
         pictureService.deletePictureBatch(deleteBatchRequest.getIds());
         return ResultUtils.success(true);
     }
    /**
     * 更新图片（仅管理员可用）
     *
     * @param pictureUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        picture.setEditTime(new Date());
        picture.setReviewStatus(ReviewStatusEnum.PASS.getValue());
        // 数据校验
        pictureService.validPicture(picture, false);
        // 判断是否存在
        long id = pictureUpdateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图片（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVO(picture, request));
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     *
     * @param pictureQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 如果spaceId不为空，查询数据库校验
        pictureService.validSpaceId(pictureQueryRequest.getSpaceId());
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     *
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 如果spaceId不为空，查询数据库校验
        pictureService.validSpaceId(pictureQueryRequest.getSpaceId());
        // 如果查询空间，需要权限校验
        if(pictureQueryRequest.getSpaceId() != null){
            boolean b = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!b, ErrorCode.NO_AUTH_ERROR);
        }
        // 查询缓存，如果缓存存在直接走缓存
        String jsonStr = JSONUtil.toJsonStr(pictureQueryRequest);
        // 对key进行md5加密
        String string = DigestUtils.md5DigestAsHex(jsonStr.getBytes());
        String key = REDIS_KEY_PREFIX + string;
        ValueOperations<String, String> redis = stringRedisTemplate.opsForValue();
        // 如果查询私有空间，那么不走缓存
        if(pictureQueryRequest.getSpaceId() == null){
            // 查询缓存
            String value = redis.get(key);
            if (ObjectUtil.isNotEmpty(value)) {
                Page<PictureVO> pictureVOPage = JSONUtil.toBean(value, Page.class);
                return ResultUtils.success(pictureVOPage);
            }
        }
        // 查询数据库
        pictureQueryRequest.setReviewStatus(ReviewStatusEnum.PASS.getValue());
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest) );
        // 获取封装类
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
        // 增加缓存
        if(pictureQueryRequest.getSpaceId() == null){
            List<PictureVO> records = pictureVOPage.getRecords();
            if (CollUtil.isNotEmpty(records)) {
                // 设置5-10分钟的随机过期时间，防止雪崩
                int expireTime = 300 + RandomUtil.randomInt(0, 300);
                redis.set(key, JSONUtil.toJsonStr(pictureVOPage), expireTime, TimeUnit.SECONDS);
            }
        }
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 分页获取当前登录用户创建的图片列表
     *
     * @param pictureQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<PictureVO>> listMyPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                               HttpServletRequest request) {
        ThrowUtils.throwIf(pictureQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        pictureQueryRequest.setUserId(loginUser.getId());
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 如果spaceId不为空，查询数据库校验
        pictureService.validSpaceId(pictureQueryRequest.getSpaceId());
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }

    /**
     * 编辑图片（给用户使用）
     *
     * @param pictureEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        pictureService.editPicture(pictureEditRequest, request);
        return ResultUtils.success(true);
    }

    /**
     * 获取表标签列表和分类列表
     *
     * @return
     */
    @GetMapping("/tags_category")
    public BaseResponse<CateGoryAndTagVO> getCategoryAndTag() {
        //获取tags表和category表和formats表
        List<Tags> tags = tagsMapper.selectList(null);
        ThrowUtils.throwIf(CollUtil.isEmpty(tags), ErrorCode.NOT_FOUND_ERROR);
        List<String> tagList = tags.stream().map(Tags::getTag)
                .collect(Collectors.toList());
        List<Category> category = categoryMapper.selectList(null);
        ThrowUtils.throwIf(CollUtil.isEmpty(category), ErrorCode.NOT_FOUND_ERROR);
        List<String> categoryList = category.stream().map(Category::getCategory)
                .collect(Collectors.toList());
        List<Formats> formats = formatsMapper.selectList(null);
        ThrowUtils.throwIf(CollUtil.isEmpty(formats), ErrorCode.NOT_FOUND_ERROR);
        List<String> formatList = formats.stream().map(Formats::getFormat)
                .collect(Collectors.toList());
        //封装数据返回
        CateGoryAndTagVO cateGoryAndTagVO = new CateGoryAndTagVO(categoryList, tagList, formatList);
        return ResultUtils.success(cateGoryAndTagVO);
    }

    /**
     * 审核图片
     *
     * @param reviewPictureRequest
     * @param request
     * @return
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> reviewPicture(@RequestBody ReviewPictureRequest reviewPictureRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(reviewPictureRequest == null, ErrorCode.PARAMS_ERROR);
        //获取数据
        Long pictureId = reviewPictureRequest.getPictureId();
        Integer reviewStatus = reviewPictureRequest.getReviewStatus();
        String reviewMessage = reviewPictureRequest.getReviewMessage();
        //参数校验
        ReviewStatusEnum enumByValue = ReviewStatusEnum.getEnumByValue(reviewStatus);
        if (enumByValue == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Picture newPicture = new Picture();
        //获取登录用户
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        //设置数据
        newPicture.setReviewerId(loginUser.getId());
        newPicture.setId(pictureId);
        newPicture.setReviewStatus(reviewStatus);
        newPicture.setReviewMessage(reviewMessage);
        newPicture.setReviewTime(new DateTime());
        boolean result = pictureService.updateById(newPicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    /**
     * 创建Ai扩图
     */
    @PostMapping("/create/ai_expansion")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<CreateOutPaintingTaskResponse.Output> createAiExtend(@RequestBody PictureAiRequest aiRequest, HttpServletRequest request){
        ThrowUtils.throwIf(aiRequest == null, ErrorCode.PARAMS_ERROR);
        // 校验登录态
        User loginUser = userService.getLoginUser(request);
        // 返回创建Ai扩图后的结果
        return ResultUtils.success(pictureService.aiExpansion(aiRequest));
    }
    /**
     * 返回Ai扩图完成后的结果
     */
    @GetMapping("/get/ai_expansion")
    public BaseResponse<GetOutPaintingTaskResponse.Output> getAiExtend(@RequestParam String taskId){
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse getOutPaintingTaskResponse = pictureService.getOutPaintingTask(taskId);
        return ResultUtils.success(getOutPaintingTaskResponse.getOutput());
    }
    // endregion
}
